package com.xdclass.mobile.mobilexdclassredis.controller;

import com.xdclass.mobile.mobilexdclassredis.RedisService;
import com.xdclass.mobile.mobilexdclassredis.domain.User;
import com.xdclass.mobile.mobilexdclassredis.mapper.UserMapper;
import com.xdclass.mobile.mobilexdclassredis.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Created whit IntelliJ IDEA
 * User:杨骏杰
 * Date:2021/3/14
 * Time:10:04
 */
@RestController
public class UserController {

    private static final String key = "userCache_";

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisService redisService;

    @Resource
    private UserService userService;

    @RequestMapping("/getUser")
    @ResponseBody
    private User getUser(String id){
        return userMapper.find(id);
    }

    @RequestMapping("getUserCache")
    @ResponseBody
    public User getUserCache(String id){

        //先从redis里面取值
        User user = (User) redisService.genValue(key+id);

        //如果拿不到则从DB取值
        if(user ==null){
            User userDB = userMapper.find(id);
            System.out.println("fresh value from DB id："+id);
            //DB非空情况刷新redis值
            if(userDB !=null) {
                redisService.set(key + id, userDB);
                return userDB;
            }
        }
        return user;
    }

    @RequestMapping("getByCache")
    @ResponseBody
    public User getByCache(String id){
        User user = userService.findById(id);
        return user;
    }

    @ResponseBody
    @RequestMapping(value = "/getexpire",method = RequestMethod.GET)
    public User findByIdTtl(String id){
        User user = new User();
        try {
            user = userService.findByIdTtl(id);
        }catch (Exception e){
            System.err.println(e.getMessage());
        }
        return user;
    }
}
